package com.jfinal.utils;

import com.jfinal.model.auth.Auth;
import com.jfinal.plugin.ehcache.CacheKit;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by xiaoyuan on 2018/2/7.
 */
public class AuthUtils {
    /**
     * 根据角色获取子权限
     * @param rolesIn 角色
     * @param parentId 父id
     * @param type 1-菜单 2-按钮 3-功能url
     * @return
     */
    public static List<Auth> getChildAuth(String rolesIn, Long parentId,Integer type){
        String[] roles = rolesIn.split(",");
        List<Auth> menu = new ArrayList<>();
        Map<Long,List<Auth>> role_auth = CacheKit.get("auth","all_role_auth");
        for(String roleId:roles){
            if(role_auth.containsKey(Long.valueOf(roleId))){
                List<Auth> auths = role_auth.get(Long.valueOf(roleId));
                //向list里面插入无重复元素
                for(Auth auth:auths){
                    if(auth.getLong("parent_id")==parentId&&auth.getInt("type").equals(type)){
                        Integer i=0;
                        for(;i<menu.size();i++){
                            if(menu.get(i).get("id").equals(auth.get("id"))){
                                break;
                            }
                        }
                        if(i>=menu.size()){
                            menu.add(auth);
                        }
                    }
                }
            }
        }
        return menu;
    }
}
